package storage

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

// LocalStorage 本地存储实现
type LocalStorage struct {
	basePath string
}

// NewLocalStorage 创建本地存储实例
func NewLocalStorage(basePath string) *LocalStorage {
	return &LocalStorage{
		basePath: basePath,
	}
}

// SaveFile 保存文件
func (ls *LocalStorage) SaveFile(filename string, reader io.Reader) (string, error) {
	// 确保目录存在
	if err := os.MkdirAll(ls.basePath, 0755); err != nil {
		return "", fmt.Errorf("failed to create directory: %v", err)
	}

	// 生成文件路径
	filePath := filepath.Join(ls.basePath, filename)

	// 创建文件
	file, err := os.Create(filePath)
	if err != nil {
		return "", fmt.Errorf("failed to create file: %v", err)
	}
	defer file.Close()

	// 写入文件内容
	_, err = io.Copy(file, reader)
	if err != nil {
		return "", fmt.Errorf("failed to write file: %v", err)
	}

	return filePath, nil
}

// GetFile 获取文件
func (ls *LocalStorage) GetFile(filename string) (*os.File, error) {
	filePath := filepath.Join(ls.basePath, filename)

	file, err := os.Open(filePath)
	if err != nil {
		return nil, fmt.Errorf("failed to open file: %v", err)
	}

	return file, nil
}

// DeleteFile 删除文件
func (ls *LocalStorage) DeleteFile(filename string) error {
	filePath := filepath.Join(ls.basePath, filename)

	if err := os.Remove(filePath); err != nil {
		return fmt.Errorf("failed to delete file: %v", err)
	}

	return nil
}

// FileExists 检查文件是否存在
func (ls *LocalStorage) FileExists(filename string) bool {
	filePath := filepath.Join(ls.basePath, filename)
	_, err := os.Stat(filePath)
	return err == nil
}

// GetFileSize 获取文件大小
func (ls *LocalStorage) GetFileSize(filename string) (int64, error) {
	filePath := filepath.Join(ls.basePath, filename)

	fileInfo, err := os.Stat(filePath)
	if err != nil {
		return 0, fmt.Errorf("failed to get file info: %v", err)
	}

	return fileInfo.Size(), nil
}

// ValidateFileType 验证文件类型
func (ls *LocalStorage) ValidateFileType(filename string, allowedTypes []string) bool {
	ext := strings.ToLower(filepath.Ext(filename))

	for _, allowedType := range allowedTypes {
		if strings.ToLower(allowedType) == ext {
			return true
		}
	}

	return false
}

// CreateDir 创建目录
func (ls *LocalStorage) CreateDir(dirPath string) error {
	fullPath := filepath.Join(ls.basePath, dirPath)
	return os.MkdirAll(fullPath, 0755)
}
